package com.zoe.vhr.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.zoe.vhr.annotation.SysLog;
import com.zoe.vhr.config.ProjectConfig;
import com.zoe.vhr.enums.BusinessType;
import com.zoe.vhr.util.R;
import com.zoe.vhr.utils.MultipartFileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @Author Zoe.Zhang
 * @Date: 2021/09/10
 * @Description
 */
@RestController
@SysLog(title = "文件上传", businessType = BusinessType.UPLOAD)
public class FileController {
    private static final Logger log = LoggerFactory.getLogger(FileController.class);
    @Autowired
    ProjectConfig projectConfig;

    @PostMapping("/upload")
    public R upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.error("    方法运行中");
        List<MultipartFile> multipartFiles = MultipartFileUtil.getMultipartFiles(request);
        for (MultipartFile multipartFile : multipartFiles) {
            String originalFilename = multipartFile.getOriginalFilename();
            int i = StrUtil.lastIndexOf(originalFilename, ".", originalFilename.length(), false);
            String suffix = StrUtil.sub(originalFilename, i, originalFilename.length() + 1);
            String fileName = UUID.randomUUID().toString();
            String datePath = DateUtil.format(DateUtil.date(), "yyyy/MM/dd/");
            String filePath = projectConfig.getUploadPath() + datePath + fileName + suffix;
            File file = new File(filePath);
            // 需要保证文件夹存在
            file.getParentFile().mkdirs();
            multipartFile.transferTo(file);
        }

        return R.success("上传成功");
    }
}
